﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using QBWeb.BLL;
using QBWeb.Models;
using QBWeb.Models.CurriculumFolder;
using QBWeb.Models.TestFolder;
using QBWeb.ViewModels;

namespace QBWeb.Controllers
{
    public class CurriculaController : Controller
    {
        private  readonly QBDbContext db = new QBDbContext();
        // GET:  Curricula
        //[Authorize(Roles ="admin")]
        /// <summary>
        /// 为管理员或教师控制器 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Index()
        {
            //if( !User.IsInRole("admin")) return Content("<script>alert('无权限');location.href='/Home/Index'</script>"); ;
            //User.Identity.GetUserId();  获取当前用户id
            var userId = User.Identity.GetUserId(); //得到当前用户Id
            //查找用户创建过的课程
            var curricula = db.Curricula.Where(a => a.TeacherId == userId).ToList();
            return View(curricula);
        }
        #region 学生加课管理
        /// <summary>
        /// 显示已加课程
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles ="students")]
        public ActionResult StuIndex()
        {
            return View();
        }
        /// <summary>
        /// 根据课程码找课程
        /// </summary>
        /// <param name="curriculaCode"></param>
        /// <returns></returns>
        public JsonResult ShowCurriculaByCode(string curriculaCode)
        {
            var temp = db.Curricula.Where(a => a.CurriCode == curriculaCode).ToList();
            if(!temp.Any()) return Json(new { msg = false });
            return Json(JsonConvert.SerializeObject(temp));
        }

        /// <summary>
        /// 学生加课
        /// </summary>
        /// <param name="studentId"></param>
        /// <param name="curriculumId"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public JsonResult JoinCurricula(string studentId,int curriculumId, string className)
        {
            try
            {
                InterfaceBll.JoinCurricula(studentId,curriculumId ,className);
                return Json(new { tf = true });
            }
            catch (Exception e)
            {
                return Json(new { tf = false, msg = e.Message });
            }
        }
        /// <summary>
        /// 退出课程
        /// </summary>
        /// <param name="curriStudent"></param>
        /// <returns></returns>
        public JsonResult QuitCurricula([Bind(Include = "CurriculumId,StudentId")] Curri_StudentTb curriStudent)
        {
            try
            {
                InterfaceBll.QuitCurricula(curriStudent);
                return Json(new {tf = true, msg = "退出成功"});
            }
            catch (Exception ex)
            {
                return Json(new {tf = false, msg = ex.Message});
            }
        }
        /// <summary>
        /// 返回学生加课界面
        /// </summary>
        /// <param name="cardIndex"></param>
        /// <returns></returns>
        public ActionResult ReturnStuCard(int cardIndex)
        {
            //var userManager= new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            //var userName = userManager.FindByIdAsync(id).Result;  //获取用户名
            switch (cardIndex)
            {
                case 0:
                    var userId = User.Identity.GetUserId(); //得到当前用户Id
                    object[] param = { userId };
                    //联合查询
                    //const string sql = "SELECT A.* " +
                    //                   "FROM Curricula A JOIN Curri_StudentTb B ON A.Id=B.CurriculumId " +
                    //                   "WHERE B.StudentId=@P0";
                    //var res = db.Database.SqlQuery<Curriculum>(sql, param);
                    //"SELECT A.*,B.NickName " +
                    //    "FROM  AspNetUsers B JOIN Curricula A ON A.TeacherId=B.Id JOIN Curri_StudentTb C ON A.Id=C.CurriculumId " +
                    //    "WHERE C.StudentId=@P0";
                    const string sql2 = "SELECT A.*,B.NickName " +
                                        "FROM  UserNameTbs B JOIN Curricula A ON A.TeacherId=B.UserId JOIN Curri_StudentTb C ON A.Id=C.CurriculumId " +
                                        "WHERE C.StudentId=@P0";
                    var res2 = db.Database.SqlQuery<CurriculumViewModels>(sql2,param);
                    return PartialView("_StuMainCard",res2.ToList());
                case 1:
                    return PartialView("_StuSearchCard");
                default:
                    return PartialView("_StuMainCard");
            }
        }
        /// <summary>
        /// 学生课程详细界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult StuDetails(int? id)
        {
            if(id==null) return HttpNotFound();
            var item = db.Curricula.Find(id);
            if (item != null)
            {
                ViewBag.CurriName = item.CurriName;
                ViewBag.Code = item.CurriCode;
                object[] param = { id, User.Identity.GetUserId() };
                //必须要符合SqlQuery<ClassesTb>中的ClassesTb中的全部属性字段，即sql语句需要把数据库字段全选出来
                //如果需要自定义则可以建在viewmodel建对应要提取出来的字段。把类放在这SqlQuery<T>面
                const string sql = "SELECT B.Id,B.CurriculumId,B.ClassName,B.InMenbers FROM Classes_StudentTb A JOIN ClassesTbs B ON A.ClassesTbId=B.Id " +
                                   "WHERE B.CurriculumId=@P0 AND A.StudentId=@P1";
                var classInfo = db.Database.SqlQuery<ClassesTb>(sql, param);
                ViewBag.ClassName = classInfo.First().ClassName;
                ViewBag.InMembers = classInfo.First().InMenbers;
                return View();
            }
            return HttpNotFound();

        }
        #endregion

        #region 学生控制器
        /// <summary>
        /// 返回学生自己课程详细界面选项卡
        /// </summary>
        /// <param name="cardIndex"></param>
        /// <returns></returns>
        public ActionResult ReturnStuDetailCard(int cardIndex)
        {
            switch (cardIndex)
            {
                case 0:
                    return PartialView("_StuDetailCard1");
                case 1:
                    return PartialView("_StuDetailCard2");
                default:
                    return PartialView("_StuDetailCard1");
            }
        }

        

        #endregion
        #region 课程管理
        /// <summary>
        /// 添加课程
        /// </summary>
        /// <param name="curriName"></param>
        /// <param name="year"></param>
        /// <param name="semester"></param>
        /// <returns></returns>
        public JsonResult AddCurriculum(string curriName,string year,string semester)
        {
            
            try { 
                InterfaceBll.AddCurriculum(curriName, year, semester,User.Identity.GetUserId());
                return Json(new{msg="",tf=true});
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message });
            }
        }
        /// <summary>
        /// 编辑课程
        /// </summary>
        /// <param name="curriName"></param>
        /// <param name="year"></param>
        /// <param name="semester"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult EditCurriculum(string curriName, string year, string semester,int Id)
        {
            try
            {
                InterfaceBll.EditCurriculum(curriName, year, semester, Id);
                return Json(new { msg = "修改成功",tf=true });
            }
            catch(Exception ex)
            {
                return Json(new{msg=ex.Message,tf =false});
            }
            
        }
        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <returns></returns>
        public JsonResult DeleteCurriculum(int curriculumId)
        {
            try
            {
                InterfaceBll.DeleteCurriculum(curriculumId);
                return Json(new {msg = "删除成功", tf = true});
            }
            catch (Exception ex)
            {
                return Json(new {msg = ex.Message, tf = false});
            }
        }

        /// <summary>
        /// 课程详情
        /// 在App_Start/RouteConfig里指定了控制器路由
        /// 前台则可以以超链接形式直接传参
        /// </summary>
        /// <param name="id"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public ActionResult Details(int? id,string className)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            //默认保存30分钟 课程id给word导入用
            var userId = User.Identity.GetUserId();
            if (userId == "") userId = "Temp";
            Session[userId] = id;
            Session.Timeout = 2 * 60; //延迟两个小时后清除

            var curriculum = db.Curricula.Find(id);
            if (curriculum == null)
            {
                return HttpNotFound();
            }
            ViewData["classInfo"] = db.ClassesTbs.FirstOrDefault(a => a.CurriculumId == id && a.ClassName == className)?.ClassName;
            return View(curriculum);
        }
        #endregion
        #region 班级管理
        /// <summary>
        /// 查询编辑
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <returns></returns>
        public JsonResult FindClasses(int curriculumId)
        {
            var findRes = db.ClassesTbs.Where(a => a.CurriculumId == curriculumId).Select(b=>new{b.ClassName,b.CurriculumId});
            if (!findRes.Any()) return Json(new {msg = false});

            var te = Json(JsonConvert.SerializeObject(findRes));
            return te;
        }
        /// <summary>
        /// 添加班级
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public JsonResult AddClasses(int curriculumId, string className)
        {
            try
            {
                InterfaceBll.AddClasses(curriculumId, className);
                return Json(new { msg = "添加成功！" ,tf=true}); ;
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message ,tf=false}); ;
            }
        }
        /// <summary>
        /// 修改班级
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <param name="newName"></param>
        /// <param name="oldName"></param>
        /// <returns></returns>
        public JsonResult EditClasses(int curriculumId, string newName,string oldName)
        {
            try
            {
                InterfaceBll.EditClasses(curriculumId, newName, oldName); 
                return Json(new { msg = "修改成功！", tf = true }); ;
            }
            catch (Exception ex)
            {
                return Json(new { msg =ex.Message,tf=false }); ;
            }
        }
        /// <summary>
        /// 删除班级
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public JsonResult DeleteClasses(int curriculumId, string className)
        {
            try
            {
                InterfaceBll.DeleteClasses(curriculumId, className);
                return Json(new { msg = "删除成功！", tf = true }); ;
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message, tf = false }); ;
            }
        }
        #endregion
        #region 知识模块管理
        /// <summary>
        /// 增加节点
        /// </summary>
        /// <param name="newTitle"></param>
        /// <param name="varyId"></param>
        /// <param name="id"></param>
        /// <param name="rank"></param>
        /// <returns></returns>
        public JsonResult AddModule(string newTitle, int id, int rank)
        {
            if (Request.UrlReferrer is null) return Json(new {msg = false}); //可能失效，目前未尝试出来
            var cid = Convert.ToInt32(Request.UrlReferrer.Segments[3].Replace("/", ""));
            try
            {
                var teacherId = User.Identity.GetUserId();
                var temp = InterfaceBll.AddModule(newTitle, teacherId, id, rank, cid).First();
               
                if (temp.Msg)
                {
                    //是否根节点
                    return temp.RootOrNot ? Json(new { msg = true }) : Json(new { msg = true, id = temp.Id, title = newTitle, varyId = temp.VaryId, rank = rank + 1 });
                }
                return Json(new { msg = false });
            }
            catch (Exception ex)
            {
                return Json(new { msg = false, disposeIt=ex.Message });
            }
        }
        /// <summary>
        /// 编辑节点
        /// </summary>
        /// <param name="newTitle"></param>
        /// <param name="varyId"></param>
        /// <param name="id"></param>
        /// <param name="rank"></param>
        /// <returns></returns>
        public JsonResult EditModule(string newTitle, int varyId, int id, int rank)
        {
            try
            {
                InterfaceBll.EditModule(newTitle, varyId, id, rank);
                return Json(new { msg = "修改成功" });
            }
            catch (Exception ex)
            {
                return ex.Message=="false" ? Json(new { msg =Convert.ToBoolean(ex.Message )}) : Json(new { msg = ex.Message });
            }
        }
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rank"></param>
        /// <returns></returns>
        public JsonResult DeleteModule(int id, int rank)
        {
            try
            {
                var temp = InterfaceBll.DeleteModule(id, rank);
                return Json(temp ? new { msg = true } : new { msg = false });
            }
            catch (Exception ex)
            {
                return Json(new {msg = ex.Message});
            }
        }
        /// <summary>
        /// 获取tree实体
        /// </summary>
        /// <returns></returns>
        public string ReturnModule()
        {
            var treeMenu = new List<TreeEntity2>();
            var cid = Convert.ToInt32(Request.UrlReferrer.Segments[3].Replace("/", ""));
            var list = db.SubjectTbs.Where(a => a.CurriculaId == cid).ToList();
            if (list.Count <= 0)
            {
                return "[]";
            }
            foreach (var item in list)
            {
                var treeEntity1 = new TreeEntity2
                {
                    label = item.SubjectName,
                    id = "1p"+item.Id,
                    varyId = cid,
                    rank = 1,
                    isOpen = true
                };
                var childList = db.BigKnowModuleTbs.Where(s => s.SubjectId == item.Id).ToList();//子级
                if (childList.Count > 0)
                {
                    var childTree1 = new List<TreeEntity2>();
                    foreach (var item2 in childList)
                    {
                        var treeEntity2 = new TreeEntity2
                        {
                            label = item2.BigModuleName,
                            id = "2p"+item2.Id,
                            varyId = item.Id,
                            rank = 2
                        };
                        var lastList = db.SmallKnowModuleTbs.Where(s => s.BigKnowModuleTbId == item2.Id).ToList();//LastList:最后一级
                        if (lastList.Count > 0)
                        {
                            var childTree2 = new List<TreeEntity2>();
                            foreach (var item3 in lastList)
                            {
                                var treeEntity3 = new TreeEntity2
                                {
                                    label = item3.SmallModuleName,
                                    id ="3p"+item3.Id,
                                    varyId = item2.Id,
                                    rank = 3
                                };
                                childTree2.Add(treeEntity3);
                            }
                            treeEntity2.children = childTree2;
                        }
                        childTree1.Add(treeEntity2);
                    }
                    treeEntity1.children = childTree1;
                }
                treeMenu.Add(treeEntity1);
            }
            var toJson = JsonConvert.SerializeObject(treeMenu);
            return toJson;
        }

        public void AddKeywords(string keywords,int id)
        {
            try
            {
                var small = db.SmallKnowModuleTbs.Find(id);
                if (small == null) return;
                small.Keywords= keywords;
                db.Entry(small).State = EntityState.Modified;
                db.SaveChanges();

            }
            catch (Exception e)
            {
                    Console.WriteLine(e);
                    throw;
            }
        }

        public string ReturnKeywords(int id)
        {
            var small=db.SmallKnowModuleTbs.Find(id);
            if (small == null) return "";
            return small.Keywords;
        }
        #endregion
        #region 知识分类管理
        /// <summary>
        /// 返回分类数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="classData"></param>
        public void ModifyQuestClass(int id,string classData)
        {
            try
            {
                InterfaceBll.ModifyQuestClass(id,classData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

        }
        /// <summary>
        /// 返回分类穿梭树数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [Authorize]
        public string ReturnTransferData(int Id)
        {
            //已分类的题
            var userId = User.Identity.GetUserId();
            var quest= db.QuestionTbs
                .Where(a => a.SmallKnowModuleTbId == Id&&a.SmallKnowModuleTbId!=null)
                .Select(a => new {a.Id, a.QuestName,haveClass=true})
                .ToList();
            
            var unclassified=db.QuestionTbs
                .Where(a=>a.SmallKnowModuleTbId==null&&a.TeacherId==userId)
                .Select(a => new { a.Id, a.QuestName , haveClass = false})
                .ToList();

          
            var toConcat = quest.Concat(unclassified).ToList(); 
            return JsonConvert.SerializeObject(toConcat);

        }
        #endregion
        /// <summary>
        /// 选项卡返回页面
        /// </summary>
        /// <param name="cardIndex"></param>
        /// <returns></returns>
        public ActionResult ReturnCard(int cardIndex)
        {
         
            switch (cardIndex)
            {
                case 0:
                    return PartialView("_Card1");
                case 1:
                    return PartialView("_Card2");
                //case 2:
                //    return PartialView("_Card3");
                //case 3:
                //    return PartialView("_Card4");
                default:
                    var userId = User.Identity.GetUserId();
                    object[] param = { Session[userId].ToString() };
                    var sql = "SELECT a.* FROM UserNameTbs a JOIN Curri_StudentTb b " +
                                        "ON a.UserId=b.StudentId WHERE b.CurriculumId=@P0";
                    var list = db.Database.SqlQuery<UserNameTb>(sql, param);
                    return PartialView ("_Card5",list);
            }
        }
        /// <summary>
        /// 获取创建者已经创建的试卷的信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ObtainTestNumber(string year,string month)
        {
            // 根据试卷的创建者来统计试卷的总份数,所以先取出所有属于该老师的试卷
            object[] param = { User.Identity.Name };
            //var sql = "select * from Issues i join TestPaperTbs t on i.id = t.issueId where t.Creator=@P0";
            //var allTest = db.Database.SqlQuery<TestPaperIssueViewModels>(sql, param);
            var allTest = db.TestPaperTbs.Include(t => t.Issue).Where(t => t.Creator == User.Identity.Name).ToList();

            // 总试卷份数
            int allTestSum = 0;
            // 本年每月的试卷份数
            int[]  everyMonthSum = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            // 本月创建的试卷
            var monthCreate = new List<object>();
            // 本月创建的试卷份数
            int monthCreateSum = 0;
            foreach (var test in allTest)
            {
                string[] date = test.CreateTime.ToString().Split('/');
                ++allTestSum;
                if(date[0] == year)
                {
                    ++everyMonthSum[Convert.ToInt32(date[1])];
                    //if (date[1] == month)
                    //{
                        //++monthCreateSum;
                        //monthCreate.Add(new
                        //{
                        //    test.TestName,
                        //    CreateTime = test.CreateTime.ToString()
                        //});
                    //}
                }
                monthCreate.Add(new
                {
                    testId = test.Id,
                    testName = test.TestName,
                    createTime = test.CreateTime.ToString(),
                    status = test.Issue.Status
                });
            }

            // 总已发布试卷份数
            int publishSum = allTest.Where(t => t.Issue.Status != 0).Count();
            // 本月发布试卷的份数，即是本月的考试次数
            int monthPublishSum = 0;
            foreach(var test in allTest.Where(t=>t.Issue.Status != 0))
            {
                string[] date = test.Issue.StartTime.ToString().Split('/');
                if(date[0] == year && date[1] == month)
                {
                    ++monthPublishSum;
                }
            }

            int unReadSum = (from t in db.TestPaperTbs
                            where t.Creator == User.Identity.Name
                            join a in db.AnswerRecordTbs on t.Id equals a.TestId
                            where a.Status == 0
                            select a).Count();

            //分别对应总试卷份数，本月创建试卷，总发布试卷份数，本月发布试卷的份数
            return Json(new { allTestSum, monthCreateSum, publishSum, monthPublishSum,monthCreate,everyMonthSum, unReadSum });
            }

        #region 未用
        // GET: Curricula/Create
        //public ActionResult Create()
        //{
        //    return View();
        //}
        //// POST: Curricula/Create
        //// 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        //// 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult Create([Bind(Include = "Id,CurriCode,CurriName,Years,Semester,Menbers,TeacherId")] Curriculum curriculum)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.Curricula.Add(curriculum);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }

        //    return View(curriculum);
        //}

        //// GET: Curricula/Edit/5
        //public ActionResult Edit(int? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    Curriculum curriculum = db.Curricula.Find(id);
        //    if (curriculum == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(curriculum);
        //}

        //// POST: Curricula/Edit/5
        //// 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        //// 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult Edit([Bind(Include = "Id,CurriCode,CurriName,ClassName,Years,Semester,Menbers,TeacherId")] Curriculum curriculum)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.Entry(curriculum).State = EntityState.Modified;
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    return View(curriculum);
        //}

        //// GET: Curricula/Delete/5
        //public ActionResult Delete(int? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    Curriculum curriculum = db.Curricula.Find(id);
        //    if (curriculum == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(curriculum);
        //}

        //// POST: Curricula/Delete/5
        //[HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        //public ActionResult DeleteConfirmed(int id)
        //{
        //    Curriculum curriculum = db.Curricula.Find(id);
        //    db.Curricula.Remove(curriculum);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}
        #endregion
        /// <summary>
        /// 报错处理
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }


  
}

 //String sql = "select * from user where id=@id";
        //SqlParameter[] paras ={
        //    new SqlParameter("@id","2"),
        //};